package com.atguigu.tingshu.common.minio.service.impl;

import com.atguigu.tingshu.common.minio.config.MinioProperties;
import com.atguigu.tingshu.common.execption.GuiguException;


import com.atguigu.tingshu.common.minio.service.FileUploadService;
import com.atguigu.tingshu.common.util.MD5;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.StatObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

//@Service
@Slf4j

public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;
    @Override
    public String fileUpload(MultipartFile file) {

        String objectKey = "";

        String originalFilename = file.getOriginalFilename();
        try {
            byte[] bytes = file.getBytes();
            String s = new String(bytes);
            String prefix = MD5.encrypt(s);
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."),originalFilename.length());
            objectKey = prefix + suffix;
            //1.检查该文件是否在minio中
            StatObjectArgs.Builder builder = StatObjectArgs.builder();
            StatObjectArgs statObjectArgs = builder
                    .bucket(minioProperties.getBucketName())
                    .object(objectKey)
                    .build();
            minioClient.statObject(statObjectArgs);
            //2.minio中有直接返回
            return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + objectKey;
        } catch (IOException e){
            log.error("上传的文件不存在的原因：{}",e.getMessage());
            throw new GuiguException(201,"该文件不存在");
        }catch (Exception e) {
            //3.minio中没有将文件上传到桶中
            log.info("该文件在桶中不存在，可以上传到minio中");
            try{
                //4.将文件上传到桶中
                PutObjectArgs.Builder putObjectArgsBuilder = PutObjectArgs.builder();
                PutObjectArgs putObjectArgs = putObjectArgsBuilder
                        .bucket(minioProperties.getBucketName())
                        .object(objectKey)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .build();
                minioClient.putObject(putObjectArgs);
                log.info("上传文件到minio中成功");
                return minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + objectKey;
            }catch(Exception subE){

                log.error("上传文件到minio中失败：{}",e.getMessage());
                throw new GuiguException(201,"上传文件到minio中失败");
            }

        }

    }
}
